package chess;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: EnterRoom
 *
 */
 public class EnterRoom extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public EnterRoom() {
		super();
	}   	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pid = request.getParameter("pid");
		String roomid = request.getParameter("rid");
		String seat = request.getParameter("seat");
		
		GameHall gameHall = (GameHall)(ContextHelper.getInstance().get("GameHall"));
		GameRoom room  = gameHall.getRoom(roomid);
		if(seat.equals("A")){
			room.setSeatA(pid);
			if(room.getSeatB()!=null){
				Player playerA = gameHall.getPlayerById(pid);
				Player playerB = gameHall.getPlayerById(room.getSeatB());
				room.addMSG("A", new RoomUserMSG(""+room.isSeatBready(),playerB.getUsername(),playerB.getId()));
				room.addMSG("B", new RoomUserMSG(""+room.isSeatAready(),playerA.getUsername(),playerA.getId()));
			}
		}else{
			room.setSeatB(pid);
			if(room.getSeatA()!=null){
				Player playerA = gameHall.getPlayerById(room.getSeatA());
				Player playerB = gameHall.getPlayerById(pid);
				room.addMSG("A", new RoomUserMSG(""+room.isSeatBready(),playerB.getUsername(),playerB.getId()));
				room.addMSG("B", new RoomUserMSG(""+room.isSeatAready(),playerA.getUsername(),playerA.getId()));
			}
		}
	}   	  	    
}